package simple;

import data.TreeNode;
import javafx.util.Pair;
import sun.reflect.generics.tree.Tree;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @author cmqzyd0700@163.com
 * @version 1.0
 * @since 2020/5/21 20:40
 */
public class No104_二叉树的最大深度 {
    public static void main(String[] args) {
        Solution104 solution104 = new Solution104();
        TreeNode data = new TreeNode(3);
        data.left = new TreeNode(9);
        data.right = new TreeNode(20);
        data.right.left = new TreeNode(15);
        data.right.right = new TreeNode(7);
        int deep = solution104.maxDepth(data);
        System.out.println(deep);
    }
}

class Solution104 {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        //迭代法
        //(结点,深度)
        Stack<Pair<TreeNode, Integer>> stack = new Stack<>();
        int deep = -3457349;
        int maxDeep = Integer.MIN_VALUE;
        stack.push(new Pair<>(root, 1));
        while (!stack.isEmpty()) {
            //当前结点检查
            Pair<TreeNode, Integer> checkTree = stack.pop();
            //初始化,因为前面不正经了
            deep = checkTree.getValue();
            //判断左右子树是否有
            if (checkTree.getKey().left == null && checkTree.getKey().right == null) {
                //子树深度
                deep = checkTree.getValue();
                maxDeep = Math.max(maxDeep, deep);
                //左子树空,右子树有
                continue;
            }
            if (checkTree.getKey().left == null) {
                stack.push(new Pair<>(checkTree.getKey().right, deep + 1));
            } else if (checkTree.getKey().right == null) {
                stack.push(new Pair<>(checkTree.getKey().left, deep + 1));
            } else {
                stack.push(new Pair<>(checkTree.getKey().left, deep + 1));
                stack.push(new Pair<>(checkTree.getKey().right, deep + 1));
            }

        }
        return maxDeep;
    }
}


    //public int maxDepth(TreeNode root) {
    //    //递归
    //    //假定这是下一个结点,左子树根节点进来
    //    int deep = 0;
    //    if (root == null) {
    //        return deep;
    //    } else {
    //        deep = 1;
    //        //结合图理解
    //        deep += Math.max(maxDepth(root.left), maxDepth(root.right));
    //    }
    //    return deep;
    //}